package com.qingcheng.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.pojo.goods.Goods;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.goods.Spu;
import com.qingcheng.service.goods.SpuService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息监听类,生成spu对应的sku页面
 */
public class MessageConsumer1 implements MessageListener {
    @Reference
    private SpuService spuService;
    @Value("${pagePath}")
    private String pagePath;
    @Autowired
    private TemplateEngine templateEngine;

    @Override
    public void onMessage(Message message) {
        //获取到spuid,生成sku的html页面
        String spuid = new String(message.getBody());
        //根据spuid找到对应的商品
        Goods goods = spuService.findGoodsById(spuid);
        //获取到sku的集合
        List<Sku> skuList = goods.getSkuList();
        //拿到spu
        Spu spu = goods.getSpu();
        //拿到每一个sku
        for (Sku sku : skuList) {
            Context context = new Context();
            Map<String, Object> dataModel = new HashMap<>();
            dataModel.put("spu", spu);
            dataModel.put("sku", sku);
            context.setVariables(dataModel);
            File dir = new File(pagePath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File dest = new File(dir, sku.getId() + ".html");
            try {
                PrintWriter printWriter = new PrintWriter(dest, "UTF-8");
                templateEngine.process("item", context, printWriter);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

    }
}
